import React, { forwardRef, useState, useImperativeHandle, ChangeEvent, useRef, useContext } from 'react';
import { Button, Modal, Input, Table, Space, Form, Pagination, Select, Radio, Image, Upload, DatePicker, Divider, DatePickerProps, TreeSelect, Switch } from 'antd';
import { FontSizeOutlined, PayCircleOutlined, BankOutlined, DesktopOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Tabs } from 'antd';
import type { TabsProps } from 'antd';
import { commonErrorMsg, deepCopy, getChangeEventValue, toastShort } from './../utils';
import SmartMapProvider from '../provider/SmartMapProvider';
import { MapTopic } from '../typings';


interface Props {
    onFinish?: Function
}


const AddMapTopicModal = (props: Props, ref: any) => {
    useImperativeHandle(ref, () => ({
        openModal: openModal
    }))

    const {
        tdt_map_token,
        mapbox_token,
        mapMountingRootId,
        uploadActionUrl,
        addMapLayerPromiseFunc,
        editMapLayerPromiseFunc,
        deleteMapLayerPromiseFunc,
        queryMapLayerPromiseFunc,
        layerManageDrawerOpen,
        setLayerManageDrawerOpen
    } = useContext(SmartMapProvider);

    const {
        onFinish
    } = props;

    const [submitLoading, setSubmitLoading] = useState(false);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [form] = Form.useForm<MapTopic>();
    const [formData, setFormData] = useState<MapTopic>({});
    const [defaultFormData] = useState<MapTopic>({
        name: "",
        layerType: 'topic',
        
    });

    const handleConfirm = async () => {
        try {
            const values = await form.validateFields();
            setSubmitLoading(true);
            let params: MapTopic = formData;
            console.log("params--->", params);
            let requestMethod = addMapLayerPromiseFunc;
            if (formData.id) {
                requestMethod = editMapLayerPromiseFunc;
            }
            requestMethod(params)
                .then(res => {
                    console.log("res", res)
                    onFinish && onFinish();
                    setIsModalOpen(false);
                    setSubmitLoading(false);
                })
                .catch(err => {
                    setSubmitLoading(false)
                    console.log("err", err)
                    toastShort('error', commonErrorMsg)
                })
        } catch (e) {

        }
    };

    const openModal = (rowData?: MapTopic) => {
        const { keys, values } = Object;
        if (rowData) {
            let _formData = deepCopy(rowData);
            const keyList = keys(_formData);
            const valueList = values(_formData)
            keyList.forEach((key, index) => {
                form.setFieldValue(key, valueList[index])
            })
            setFormData(_formData);
        } else {
            let _formData = deepCopy(defaultFormData);
            const keyList = keys(_formData);
            const valueList = values(_formData)
            keyList.forEach((key, index) => {
                form.setFieldValue(key, valueList[index])
            })
            setFormData(_formData);
        }
        setIsModalOpen(true);
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };

    const handleSetFormData = (target: string, value: any) => {
        let _formData = formData;
        //@ts-ignore
        _formData[target] = value;
        setFormData(deepCopy(_formData));
    };

    const onNameTextChange = (e: ChangeEvent<HTMLInputElement>) => {
        handleSetFormData('name', getChangeEventValue(e));
    }

    return (
        <Modal
            title={'新增地理专题'}
            open={isModalOpen}
            onOk={handleConfirm}
            onCancel={handleCancel}
            okText={'确 认'}
            cancelText={'取 消'}
            width={612}
            maskClosable={false}
            confirmLoading={submitLoading}
            centered
        >
            <div className='custom-modal-container'>
                <Form
                    size={'large'}
                    form={form}
                    layout={'horizontal'}
                    autoComplete="off"
                    labelAlign={'right'}
                    labelCol={{ span: 3 }}
                    style={{ width: '100%' }}
                >
                    <Form.Item
                        label="名称"
                        name={'name'}
                        rules={[{ required: true, message: '请输入专题名称' }]}
                    >
                        <Input
                            placeholder='请输入专题名称'
                            style={{ width: '426px' }}
                            maxLength={20}
                            value={formData.name}
                            onChange={onNameTextChange}
                            allowClear
                        />
                    </Form.Item>
                </Form>
            </div>
        </Modal>
    )
}


export default forwardRef(AddMapTopicModal)